//
//  XGStatusPicturesView.swift
//  TodayNews
//
//  Created by monkey on 2020/2/23.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import Kingfisher
import JXPhotoBrowser

class XGStatusPicturesView: UIView
{
    /// 缩略图数组
    var thumbImageList: [XGImageInfo]? {
        didSet {
            guard let thumbImageList = thumbImageList,thumbImageList.count > 0 else {
                return
            }
            
            // 隐藏所有的图片视图
            subviews.forEach {$0.isHidden = true}
            
            if thumbImageList.count == 1 {
                // 一张图 等比例缩放
                let imageInfo = thumbImageList[0]
                if imageInfo.url == nil {
                    return
                }
                
                let height = floor(TodayNews_Screen_Width / CGFloat(imageInfo.width) * CGFloat(imageInfo.height))
                let firstImageView = subviews[0] as! UIImageView
                firstImageView.isHidden = false
                firstImageView.frame = CGRect(x: 0, y: kPicturesViewOuterMargin, width: TodayNews_Screen_Width, height: height)
                firstImageView.kf.setImage(with: URL(string: imageInfo.url!), options: [.processor(DownsamplingImageProcessor(size: firstImageView.bounds.size))])
            } else {
                // 多图 先将第一张图片复位
                let firstImageView = subviews[0]
                firstImageView.frame = CGRect(x: kPicturesViewOuterMargin, y: kPicturesViewOuterMargin, width: kPicturesViewItemWidth, height: kPicturesViewItemWidth)
                // 逐个赋值
                var index: Int = 0
                for imageInfo in thumbImageList {
                    let imageView = subviews[index] as! UIImageView
                    imageView.isHidden = false
                    if imageInfo.url != nil {
                        imageView.kf.setImage(with: URL(string: imageInfo.url!), options: [.processor(DownsamplingImageProcessor(size: firstImageView.bounds.size))])
                    }
                    
                    index += 1
                    thumbImageList.count == 4 && index == 2 ? index += 1 : ()
                }
            }
        }
    }
    /// 大图数组
    var largeImagelist: [XGImageInfo]?
    
    // MARK: - 构造方法
    
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - 私有j扩展

private extension XGStatusPicturesView
{
    @objc func tapImageAction(tapGesture: UITapGestureRecognizer) -> Void
    {
        guard let largeImagelist = largeImagelist, largeImagelist.count > 0 else {
                return
        }
                
        let browser = JXPhotoBrowser()
        // 使用自定义cell
        browser.cellClassAtIndex = { _ in XGLoadingPictureProgressCell.self }
        // 多少张
        browser.numberOfItems = { return largeImagelist.count }
        // 设置图片
        browser.reloadCellAtIndex = {[weak self] context in
            // 对应的外部index
            let outerIndex = largeImagelist.count == 4 && context.index > 1 ? context.index + 1 : context.index
            if let browserCell = context.cell as? XGLoadingPictureProgressCell,
                let url = largeImagelist[context.index].url,
                let imageView = self?.subviews[outerIndex] as? UIImageView {
                browserCell.reloadImage(url: url, placeholderImage: imageView.image)
            }
        }
        // 更丝滑的Zoom动画
        browser.transitionAnimator = JXPhotoBrowserSmoothZoomAnimator(transitionViewAndFrame: { [weak self] (index, destinationView) -> JXPhotoBrowserSmoothZoomAnimator.TransitionViewAndFrame? in
            // 对应的外部index
            let outerIndex = largeImagelist.count == 4 && index > 1 ? index + 1 : index
            guard let imageView = self?.subviews[outerIndex] as? UIImageView else {
                return nil
            }
            
            let transitionView = UIImageView(image: imageView.image!)
            transitionView.contentMode = .scaleAspectFill
            transitionView.clipsToBounds = true
            let thumbnailFrame = self?.convert(imageView.frame, to: destinationView)
            return (transitionView, thumbnailFrame ?? CGRect.zero)
        })
        
        // 展示视图
        var index = tapGesture.view?.tag ?? 0  // 外部index
        index = largeImagelist.count == 4 && index > 2 ? index - 1 : index
        browser.pageIndicator = JXPhotoBrowserNumberPageIndicator()
        browser.pageIndex = index
        browser.show()
    }
    
    /// 设置界面
    func setUpUI() -> Void
    {
        backgroundColor = UIColor.white
        clipsToBounds = true
        // 添加图片视图
        for i in 0..<kPicturesViewColumns * kPicturesViewColumns {
            let row = i / kPicturesViewColumns
            let column = i % kPicturesViewColumns
            let x = kPicturesViewOuterMargin + CGFloat(column) * (kPicturesViewInnerMargin + kPicturesViewItemWidth)
            let y = kPicturesViewOuterMargin + CGFloat(row) * (kPicturesViewInnerMargin + kPicturesViewItemWidth)
            let imageView = UIImageView()
            imageView.backgroundColor = UIColor.white
            imageView.contentMode = .center
            imageView.clipsToBounds = true
            imageView.tag = i
            imageView.isUserInteractionEnabled = true
            imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapImageAction(tapGesture:))))
            addSubview(imageView)
            imageView.frame = CGRect(x: x, y: y, width: kPicturesViewItemWidth, height: kPicturesViewItemWidth)
        }
    }
}
